import * as types from './mutationTypes'
import {
  saveSearch,
  deleteSearch,
  clearSearch,
  savePlay,
  setCurrentIndex,
  savePlayList
} from 'utils/cache'
import { findIndex } from 'utils'

const actions = {
  // 保存搜索记录
  saveSearchHistory: ({
    commit
  }, query) => {
    commit(types.SET_SEARCH_HISTORY, saveSearch(query))
  },
  // 删除搜索记录
  deleteSearchHistory: ({
    commit
  }, query) => {
    commit(types.SET_SEARCH_HISTORY, deleteSearch(query))
  },
  // 清空搜索记录
  clearSearchHistory: ({
    commit
  }) => {
    commit(types.SET_SEARCH_HISTORY, clearSearch())
  },
  // 保存播放记录
  savePlayHistory: ({
    commit
  }, song) => {
    commit(types.SET_PLAY_HISTORY, savePlay(song))
  },
  // 设置当前歌曲index
  setCurrentIndex: ({
    commit
  }, index) => {
    commit(types.SET_CURRENT_INDEX, setCurrentIndex(index))
  },
  setPlayList: ({
    commit
  }, list) => {
    commit(types.SET_PLAY_LIST, savePlayList(list))
  },
  // 删除歌曲列表
  deleteSongList: ({
    commit
  }) => {
    commit(types.SET_CURRENT_INDEX, 0)
    commit(types.SET_PLAY_LIST, [])
    commit(types.SET_PLAYING_STATE, false)
  },
  deleteSong: ({
    commit,
    state
  }, song) => {
    let songList = state.playList
    // let currentIndex = state.currentIndex
    let index = findIndex(songList, song)
    songList.splice(index, 1)
    commit(types.SET_PLAY_LIST, songList)
    if (!songList.length) {
      commit(types.SET_PLAYING_STATE, false)
    }
  }
}

export default actions
